package com.lw.leetcode.tree.b;

import com.lw.leetcode.tree.TreeNode;

import java.util.LinkedList;
import java.util.Queue;

/**
 * Created with IntelliJ IDEA.
 * tree
 * 1161. 最大层内元素和
 *
 * @author liw
 * @version 1.0
 * @date 2021/10/28 15:02
 */
public class MaxLevelSum {

    public static void main(String[] args) {
        MaxLevelSum test = new MaxLevelSum();
        int i = test.maxLevelSum(TreeNode.getInstance4());
        System.out.println(i);
    }


    public int maxLevelSum(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        queue.add(null);
        int sum = 0;
        int index = 1;
        int maxIndex = 1;
        int max = root.val;
        while (queue.size() > 1) {
            TreeNode node = queue.poll();
            if (node == null) {
                if (sum > max) {
                    max = sum;
                    maxIndex = index;
                }
                index++;
                sum = 0;
                queue.add(null);
            } else {
                if (node.left != null) {
                    queue.add(node.left);
                }
                if (node.right != null) {
                    queue.add(node.right);
                }
                sum += node.val;
            }
        }
        if (sum > max) {
            maxIndex = index;
        }
        return maxIndex;
    }

}
